const http = require('http');
const server = http.createServer();
const { readFileSync } = require('fs');

server.listen(3002, () =>
	console.log('服务器开启了，点击访问：http://127.0.0.1:3002')
);



server.on('request', (request, response) => {
	const routeList = [setCors, getHomePage];

	for (const route of routeList) {
		let nextFlag = false;

		route(request, response, () => {
			nextFlag = true;
		});

		if (!nextFlag) {
			return;
		}
	}

    response.end('not Found');
});

// 获取首页的路由
function getHomePage(request, response, next) {
	if (request.url !== '/') {
		next();
		return;
	}

	response.end(readFileSync('./index.html', 'utf-8'));
	return;
}

// cors设置
function setCors(request, response, next) {
    response.setHeader('Content-Type', 'text/html;charset=utf-8'); 
    response.setHeader('Access-Control-Allow-Origin', ['http://localhost:3002']); 
    response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); 
    response.setHeader('Access-Control-Allow-Headers', '*'); 
    response.setHeader('Access-Control-Allow-Credentials', 'true')

	next();
}
